package com.changgou.test.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Lock2 {

    public static void main(String[] args) {

        Cond cond = new Cond();
        new Thread(()-> {
            for(int i =0; i<10 ;i++){
                cond.incr();
            }

        },"ac").start();

        new Thread(()-> {
            for(int i =0; i<10 ;i++){
                try {
                    cond.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        },"sv").start();
    }


static class  Cond {

    private int nums =0;

    Lock locksk = new ReentrantLock();
    Condition condition = locksk.newCondition();

    public  void incr () {
        try{
         //   locksk.lock();
            while (nums  != 0){
                condition.await();
            }
            nums++;
            System.out.println(Thread.currentThread().getName()+"-->"+nums);
            condition.signalAll();
        } catch (Exception e){
            System.out.println(e);
        }finally {
         //   locksk.unlock();
        }
    }

    public   void decr () throws InterruptedException {
        try {
           // locksk.lock();
            while (nums == 0) {
                condition.await();
            }
            nums--;
            System.out.println(Thread.currentThread().getName()+"-->"+nums);
            condition.signalAll();
        } catch (Exception e) {
            System.out.println(e);
        } finally{
        //     locksk.unlock();
        }
    }

}

}